import { createHash } from 'crypto'
import redis from '../config/redis.js'
import sharp from 'sharp'

export const imageCache = async (req, res, next) => {
  if (!req.url.includes('/uploads/')) return next()

  const isThumbnail = req.query.thumbnail === 'true'
  const cacheKey = `image:${createHash('md5').update(req.url).digest('hex')}`

  try {
    // 检查缓存
    const cached = await redis.getBuffer(cacheKey)
    if (cached) {
      res.set('Content-Type', 'image/jpeg')
      return res.send(cached)
    }

    // 处理图片
    if (isThumbnail) {
      const image = await sharp(req.file.buffer)
        .resize(200, 200, {
          fit: 'cover',
          position: 'centre'
        })
        .jpeg({ quality: 80 })
        .toBuffer()

      // 缓存缩略图
      await redis.setex(cacheKey, 86400, image) // 24小时缓存
      res.set('Content-Type', 'image/jpeg')
      res.send(image)
    } else {
      next()
    }
  } catch (error) {
    console.error('Image cache error:', error)
    next()
  }
} 